package com.sl.core.job.scheduler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.core.job.ProcessJobConfig;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.function.Function;

@Slf4j
public class JobTask implements Job {


    private static Function<String, Object> PROCESS_CALL_BACK = null;

    public static void setCallBack(Function<String, Object> callBack) {
        PROCESS_CALL_BACK = callBack;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        log.info("Wx " + new Date() + jobExecutionContext);
        log.info("*****************************************{},{}", new Date(), jobExecutionContext);
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobDataMap j = jobDetail.getJobDataMap();

        JobKey key = jobDetail.getKey();
        String name = key.getName();

        String jobId = StrUtil.replace(name, ProcessJobConfig.SCHEDULE_NAME, "");
        log.info("***************************************** jobId:{}", jobId);
        log.info("*****************************************jobDetail:{}", jobDetail);
        log.info("*****************************************jobDataMap:{}", j);
        Scheduler scheduler = jobExecutionContext.getScheduler();
        try {
            //jobId找到关联的流程，找到了然后执行
            if (ObjectUtil.isNull(PROCESS_CALL_BACK)) {
                return;
            }
            Object obj = PROCESS_CALL_BACK.apply(jobId);
            log.info("*****************************************result:{}", obj);
        } catch (Exception e) {
            log.error("job is error : {}", e);
            e.printStackTrace();
        }
    }

}
